"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { signIn as authSignIn } from "@/lib/auth";
import { createClient } from "@/lib/supabase/server";
import { compare, hash } from "bcrypt";
import { db } from "@/lib/db";
import { users, userSchema } from "@supersavely/db/schema";

export async function login(formData: FormData) {
  const supabase = createClient();

  // type-casting here for convenience
  // in practice, you should validate your inputs
  const data = {
    email: formData.get("email") as string,
    password: formData.get("password") as string,
  };
  console.log(data);
  if (!process.env.LOCAL_AUTH) {
    const { error } = await supabase.auth.signInWithPassword(data);

    if (error) {
      console.error(error);
      redirect("/error");
    }
  } else {
    // Need send password to server to use compare to check the hash
    data.passwordHash = data.password;
    data.mode = "signIn";
    const validateData = userSchema.parse(data);
    if (validateData.mode === "signIn") {
      const response: any = await authSignIn("credentials", {
        ...validateData,
        redirectTo: "/",
      });
      if (!response?.error) {
        redirect("/error");
      }

      try {
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        // Process response here
        console.log("Login Successful", response);
      } catch (error: any) {
        console.error("Login Failed:", error);
        redirect("/error");
      }
    }
  }

  revalidatePath("/", "layout");
  redirect("/");
}

export async function signup(formData: FormData) {
  const supabase = createClient();

  // type-casting here for convenience
  // in practice, you should validate your inputs
  const data = {
    email: formData.get("email") as string,
    password: formData.get("password") as string,
  };

  const { error } = await supabase.auth.signUp(data);

  if (error) {
    redirect("/error");
  }

  revalidatePath("/", "layout");
  redirect("/");
}
